package jmine.tec.web.servlet.util;

import java.util.concurrent.ExecutorService;

import javax.servlet.ServletContext;

import jmine.tec.utils.concurrent.SimpleThreadPoolExecutor;

/**
 * @author takeshi
 */
public final class ServletExecutor {

    /**
     * To prevent construction
     */
    private ServletExecutor() {
    }

    public static final String EXECUTOR_SERVICE_NAME = ServletExecutor.class + "$Executor";

    public static final String SCHEDULED_EXECUTOR_SERVICE_NAME = ServletExecutor.class + "$ScheduledExecutor";

    /**
     * @param context the {@link ServletContext}
     * @return {@link ExecutorService}
     */
    public static ExecutorService getOrCreateExecutorService(ServletContext context) {
        synchronized (context) {
            ExecutorService ex = (ExecutorService) context.getAttribute(EXECUTOR_SERVICE_NAME);
            if (ex != null) {
                return ex;
            }
            ex = new SimpleThreadPoolExecutor();
            context.setAttribute(EXECUTOR_SERVICE_NAME, ex);
            return ex;
        }
    }

    /**
     * Desliga o(s) executor(es)
     * 
     * @param context {@link ServletContext}
     * @param interruptRunningTasks boolean
     */
    public static void shutdownExecutorServices(ServletContext context, boolean interruptRunningTasks) {
        synchronized (context) {
            shutdown((ExecutorService) context.getAttribute(EXECUTOR_SERVICE_NAME), interruptRunningTasks);
            context.removeAttribute(EXECUTOR_SERVICE_NAME);
            shutdown((ExecutorService) context.getAttribute(SCHEDULED_EXECUTOR_SERVICE_NAME), interruptRunningTasks);
            context.removeAttribute(SCHEDULED_EXECUTOR_SERVICE_NAME);
        }
    }

    /**
     * @param es {@link ExecutorService}
     * @param interruptRunningTasks boolean
     */
    private static void shutdown(ExecutorService es, boolean interruptRunningTasks) {
        if (es != null) {
            if (interruptRunningTasks) {
                es.shutdownNow();
            } else {
                es.shutdown();
            }
        }
    }

}
